<template>
    <div ref="chartRef" :style="{ width: width, height: height }"></div>
  </template>
  
  <script setup name="LineChart">
  import { ref, onMounted, onUnmounted, watch } from 'vue'
  import * as echarts from 'echarts'
  
  const props = defineProps({
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '400px'
    },
    title: {
      type: String,
      default: ''
    },
    xAxisData: {
      type: Array,
      default: () => []
    },
    seriesData: {
      type: Array,
      default: () => []
    },
    legend: {
      type: Array,
      default: () => []
    },
    legendFontSize: {
      type: Number,
      default: 14 // 默认字号
    },
    colors: {
        type: Array,
        default: () => ['#2d8cf0', '#19be6b', '#ff9900']  // 默认颜色
    }
  })
  
  const chartRef = ref(null)
  let chartInstance = null
  
  const initChart = () => {
    if (!chartRef.value) return
  
    chartInstance = echarts.init(chartRef.value)
    const option = {
      title: {
        text: props.title,
        left: 'left',  // 标题靠左显示
        top: '10',     // 距离顶部10px
        textStyle: {
            fontSize: 16,
            fontWeight: 'normal',
        }
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: props.legend,
        textStyle: {
          fontSize: props.legendFontSize
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: props.xAxisData
      },
      yAxis: {
        type: 'value'
      },
      series: props.seriesData.map((data, index) => ({
        name: props.legend[index],
        type: 'line',
        data: data,
        smooth: true,
        areaStyle: {
            opacity: 0.1
        },
        itemStyle: {
            color: props.colors[index % props.colors.length]  // 循环使用颜色
        },
        lineStyle: {
            color: props.colors[index % props.colors.length]
        }
      }))
    }
    chartInstance.setOption(option)
  }
  
  onMounted(() => {
    initChart()
  })
  
  onUnmounted(() => {
    if (chartInstance) {
      chartInstance.dispose()
      chartInstance = null
    }
  })
  
  watch(
    () => [props.xAxisData, props.seriesData, props.legend, props.title, props.legendFontSize],
    () => {
      if (chartInstance) {
        initChart()
      }
    },
    { deep: true }
  )
  </script>
